import 'package:dio/dio.dart';
import '../core/api_client.dart';
import '../core/api_response.dart';
import '../core/api_logger.dart';
import '../models/user.dart';
import '../models/auth_token.dart';
import '../models/login_request.dart';

class AuthService {
  final ApiClient _apiClient;
  
  AuthService({ApiClient? apiClient}) 
      : _apiClient = apiClient ?? ApiClient();

  Future<ApiResponse<LoginResponse>> login(LoginRequest request) async {
    print('🔐 [AUTH_SERVICE] 开始用户登录...');
    try {
      final response = await _apiClient.post(
        '/api/auth/login',
        data: request.toJson(),
      );
      
      final loginResponse = LoginResponse.fromJson(response.data);
      print('✅ [AUTH_SERVICE] 登录成功: ${loginResponse.user.username}');
      
      return ApiResponse.success(
        data: loginResponse,
        message: loginResponse.message,
        statusCode: response.statusCode ?? 200,
      );
    } on DioException catch (e) {
      print('❌ [AUTH_SERVICE] 登录失败: ${e.type} - ${e.message}');
      return _handleAuthError(e);
    } catch (e) {
      print('💥 [AUTH_SERVICE] 登录未知错误: $e');
      return ApiResponse.error(
        error: '登录失败: $e',
        statusCode: 500,
      );
    }
  }

  Future<ApiResponse<User>> register(RegisterRequest request) async {
    print('📝 [AUTH_SERVICE] 开始用户注册...');
    try {
      final response = await _apiClient.post(
        '/api/auth/register',
        data: request.toJson(),
      );
      
      final user = User.fromJson(response.data['user'] ?? response.data);
      print('✅ [AUTH_SERVICE] 注册成功: ${user.username}');
      
      return ApiResponse.success(
        data: user,
        message: '注册成功',
        statusCode: response.statusCode ?? 201,
      );
    } on DioException catch (e) {
      print('❌ [AUTH_SERVICE] 注册失败: ${e.type} - ${e.message}');
      return _handleAuthError(e);
    } catch (e) {
      print('💥 [AUTH_SERVICE] 注册未知错误: $e');
      return ApiResponse.error(
        error: '注册失败: $e',
        statusCode: 500,
      );
    }
  }

  Future<ApiResponse<AuthToken>> refreshToken(String refreshToken) async {
    print('🔄 [AUTH_SERVICE] 开始刷新Token...');
    try {
      final response = await _apiClient.post(
        '/api/auth/refresh',
        data: {'refreshToken': refreshToken},
      );
      
      final token = AuthToken.fromJson(response.data);
      print('✅ [AUTH_SERVICE] Token刷新成功');
      
      return ApiResponse.success(
        data: token,
        message: 'Token刷新成功',
        statusCode: response.statusCode ?? 200,
      );
    } on DioException catch (e) {
      print('❌ [AUTH_SERVICE] Token刷新失败: ${e.type} - ${e.message}');
      return _handleAuthError(e);
    } catch (e) {
      print('💥 [AUTH_SERVICE] Token刷新未知错误: $e');
      return ApiResponse.error(
        error: 'Token刷新失败: $e',
        statusCode: 500,
      );
    }
  }

  Future<ApiResponse<User>> getProfile() async {
    print('👤 [AUTH_SERVICE] 获取用户信息...');
    try {
      final response = await _apiClient.get('/api/auth/profile');
      
      final user = User.fromJson(response.data);
      print('✅ [AUTH_SERVICE] 获取用户信息成功: ${user.username}');
      
      return ApiResponse.success(
        data: user,
        message: '获取用户信息成功',
        statusCode: response.statusCode ?? 200,
      );
    } on DioException catch (e) {
      print('❌ [AUTH_SERVICE] 获取用户信息失败: ${e.type} - ${e.message}');
      return _handleAuthError(e);
    } catch (e) {
      print('💥 [AUTH_SERVICE] 获取用户信息未知错误: $e');
      return ApiResponse.error(
        error: '获取用户信息失败: $e',
        statusCode: 500,
      );
    }
  }

  Future<ApiResponse<void>> logout() async {
    print('🚪 [AUTH_SERVICE] 用户登出...');
    try {
      final response = await _apiClient.post('/api/auth/logout');
      
      print('✅ [AUTH_SERVICE] 登出成功');
      return ApiResponse.success(
        message: '登出成功',
        statusCode: response.statusCode ?? 200,
      );
    } on DioException catch (e) {
      print('❌ [AUTH_SERVICE] 登出失败: ${e.type} - ${e.message}');
      // 登出失败也认为是成功，清理本地状态
      return ApiResponse.success(message: '登出成功');
    } catch (e) {
      print('💥 [AUTH_SERVICE] 登出未知错误: $e');
      // 登出失败也认为是成功，清理本地状态
      return ApiResponse.success(message: '登出成功');
    }
  }

  Future<ApiResponse<void>> forgotPassword(ForgotPasswordRequest request) async {
    print('📧 [AUTH_SERVICE] 发送找回密码邮件...');
    try {
      final response = await _apiClient.post(
        '/api/auth/forgot-password',
        data: request.toJson(),
      );
      
      print('✅ [AUTH_SERVICE] 找回密码邮件发送成功');
      return ApiResponse.success(
        message: '找回密码邮件已发送，请检查您的邮箱',
        statusCode: response.statusCode ?? 200,
      );
    } on DioException catch (e) {
      print('❌ [AUTH_SERVICE] 发送找回密码邮件失败: ${e.type} - ${e.message}');
      return _handleAuthError(e);
    } catch (e) {
      print('💥 [AUTH_SERVICE] 发送找回密码邮件未知错误: $e');
      return ApiResponse.error(
        error: '发送找回密码邮件失败: $e',
        statusCode: 500,
      );
    }
  }

  Future<ApiResponse<User>> updateProfile(User user) async {
    print('✏️ [AUTH_SERVICE] 更新用户信息...');
    try {
      final response = await _apiClient.put(
        '/api/auth/profile',
        data: user.toJson(),
      );
      
      final updatedUser = User.fromJson(response.data);
      print('✅ [AUTH_SERVICE] 用户信息更新成功');
      
      return ApiResponse.success(
        data: updatedUser,
        message: '用户信息更新成功',
        statusCode: response.statusCode ?? 200,
      );
    } on DioException catch (e) {
      print('❌ [AUTH_SERVICE] 更新用户信息失败: ${e.type} - ${e.message}');
      return _handleAuthError(e);
    } catch (e) {
      print('💥 [AUTH_SERVICE] 更新用户信息未知错误: $e');
      return ApiResponse.error(
        error: '更新用户信息失败: $e',
        statusCode: 500,
      );
    }
  }

  ApiResponse<T> _handleAuthError<T>(DioException error) {
    String message;
    int statusCode = error.response?.statusCode ?? 500;
    
    switch (error.type) {
      case DioExceptionType.connectionTimeout:
        message = '连接超时，请检查网络';
        break;
      case DioExceptionType.sendTimeout:
        message = '发送超时，请重试';
        break;
      case DioExceptionType.receiveTimeout:
        message = '接收超时，请重试';
        break;
      case DioExceptionType.badResponse:
        if (statusCode == 401) {
          message = '用户名或密码错误';
        } else if (statusCode == 403) {
          message = '访问被禁止';
        } else if (statusCode == 422) {
          message = error.response?.data?['message'] ?? '请求参数错误';
        } else if (statusCode >= 500) {
          message = '服务器错误，请稍后重试';
        } else {
          message = error.response?.data?['message'] ?? '请求失败';
        }
        break;
      case DioExceptionType.cancel:
        message = '请求已取消';
        break;
      case DioExceptionType.connectionError:
        message = '网络连接失败，请检查网络设置';
        break;
      case DioExceptionType.unknown:
      default:
        message = '未知错误，请重试';
        break;
    }
    
    return ApiResponse.error(
      error: message,
      statusCode: statusCode,
    );
  }
}